package com.streaminggbs.common.log;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.streaminggbs.common.utils.IDManager;
import com.streaminggbs.entity.SysAuthUser;
import com.streaminggbs.entity.SysAuthUserOperationLogEntity;
import com.streaminggbs.interfaces.SysAuthUserOperationLogService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;


@Aspect
@Component
@Order(1)
@Slf4j
public class SysAuthOperationLogAspect {

    @Autowired
    private SysAuthUserOperationLogService sysAuthUserOperationLogService;

    /**定义切点表达式,指定通知功能被应用的范围*/
    @Pointcut("execution(public * com.streaminggbs.controller.*.*(..))")
    public void sysAuthOperationLog() {
    }

    @Before("sysAuthOperationLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    /**value切入点位置
     * returning 自定义的变量，标识目标方法的返回值,自定义变量名必须和通知方法的形参一样
     * 特点：在目标方法之后执行的,能够获取到目标方法的返回值，可以根据这个返回值做不同的处理
     */
    @AfterReturning(value = "sysAuthOperationLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /**通知包裹了目标方法，在目标方法调用之前和之后执行自定义的行为
    ProceedingJoinPoint切入点可以获取切入点方法上的名字、参数、注解和对象*/
    @Around("sysAuthOperationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable
    {
        Date startTime = new Date();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        SysAuthUserOperationLogEntity sysAuthUserOperationLogEntity = new SysAuthUserOperationLogEntity();
        //前面是前置通知，后面是后置通知
        Object result = joinPoint.proceed();
        HttpSession session = request.getSession();
        if(session != null){
            SysAuthUser user = (SysAuthUser) session.getAttribute("user");
            if(user != null){
                sysAuthUserOperationLogEntity.setUserId(user.getUserid());
            }
        }
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        if (null != apiOperation) {
            sysAuthUserOperationLogEntity.setOperationContent(apiOperation.value());
        }
        String urlStr = request.getRequestURL().toString();
        sysAuthUserOperationLogEntity.setId(IDManager.nextId());
        sysAuthUserOperationLogEntity.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        sysAuthUserOperationLogEntity.setIp(getIpAddr(request));
        sysAuthUserOperationLogEntity.setMethod(request.getMethod());
        sysAuthUserOperationLogEntity.setParameter(getParameter(method, joinPoint.getArgs()));
        sysAuthUserOperationLogEntity.setResult(JSONObject.toJSONString(result));
        sysAuthUserOperationLogEntity.setEndTime(new Date());
        sysAuthUserOperationLogEntity.setStartTime(startTime);
        sysAuthUserOperationLogEntity.setUri(request.getRequestURI());
        sysAuthUserOperationLogEntity.setUrl(request.getRequestURL().toString());
        sysAuthUserOperationLogEntity.setCreateTime(new Date());
        sysAuthUserOperationLogService.save(sysAuthUserOperationLogEntity);
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     * @param method
     * @param args
     * @return
     */
    private String getParameter(Method method, Object[] args)
    {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>(10);
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        }
        return JSONArray.toJSONString(argList);
    }

    /**
     * 获取IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
